//
//  NSDictionary+Safe.m
//  DebugDemo
//
//  Created by XFB on 2018/11/9.
//  Copyright © 2018年 ZhouCheng. All rights reserved.
//

#import "NSDictionary+Safe.h"
#import "NSObject+Swizzling.h"

@implementation NSDictionary (Safe)


+ (void)load
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        // 获取原生方法以及设置需要交换的方法  两种初始化方式都涵盖到，防止因为涵盖不周到导致的崩溃。
        [objc_getClass("__NSPlaceholderDictionary") swizzleSelector:@selector(initWithObjects:forKeys:count:)
                                               withSwizzledSelector:@selector(zc_safeInitWithObjects:forKeys:count:)];
//        [self swizzleObjectMethod:@selector(initWithObjects:forKeys:count:)
//                       withMethod:@selector(zc_safeInitWithObjects:forKeys:count:)];
        
        [self swizzleClassMethod:@selector(dictionaryWithObjects:forKeys:count:)
                      withMethod:@selector(zc_safeDictionaryWithObjects:forKeys:count:)];
    });
}

//+ (instancetype)zc_safeInitWithObjects:(const id [])objects forKeys:(const id<NSCopying> [])keys count:(NSUInteger)count
- (instancetype)zc_safeInitWithObjects:(const id [])objects
                               forKeys:(const id<NSCopying> [])keys count:(NSUInteger)count
{
    id safeObjectsValues[count];
    id safeObjectsKeys[count];

    NSUInteger j = 0;
    for (NSUInteger i = 0; i < count; i ++) {
        id key = keys[i];
        id value = objects[i];

        /// 如果key 和 value 有为nil 空的时候，跳过
        if (!key || !value) {
            /**
             break是结束整个循环，而continue是结束本次循环（跳过下一步），
             为了循环的继续，我们就必须选择continue.
             */
            continue;
        }
        /// key - value 相互对应的
        safeObjectsKeys[j] = key;
        safeObjectsValues[j] = value;
        j ++;
    }
    // 处理完毕之后，我们返回新的kay、value以及count，此时我们已经将nil的key&value清除掉了。
    return [self zc_safeInitWithObjects:safeObjectsValues forKeys:safeObjectsKeys count:j];
}

/// 我觉得这样的方式可以
//- (instancetype)zc_safeInitWithObjects:(id *)objects forKeys:(id *)keys count:(NSUInteger)count
//{
//    for (NSUInteger i = 0; i < count; i ++) {
//        if(!keys[i]) keys[i] = @"";
//        if(!objects[i]) objects[i] = @"";
//    }
//    return [self zc_safeDictionaryWithObjects:objects forKeys:keys count:count];
//}

- (instancetype)zc_safeDictionaryWithObjects:(const id [])objects forKeys:(const id<NSCopying> [])keys count:(NSUInteger)count
{
    id safeObjectsValues[count];
    id safeObjectsKeys[count];
    
    NSUInteger j = 0;
    for (NSUInteger i = 0; i < count; i ++) {
        id key = keys[i];
        id value = objects[i];
        
        if (!key || !value) {
            continue;
        }
        if (!value) {
            value = [NSNull null];
        }
        safeObjectsKeys[j] = key;
        safeObjectsValues[j] = value;
        j++;
    }
    
    return [self zc_safeDictionaryWithObjects:safeObjectsValues forKeys:safeObjectsKeys count:j];
}

@end
